import axios from 'axios'
/**
 * 注意：
 * 此redmine功能依赖：
 * *、对1688等excel文件格式有依赖，
 * *、对worknotes中分销商选项列表、项目代号等值有依赖， *
 * 这些外部依赖变化后，需要跟随修改代码
 */

var config = {
  hostname: '',
  apiKey: ''
}

var logger = console

export function setLogger (loggerIn) {
  if (loggerIn) {
    logger = loggerIn
  } else {
    logger = console
  }
}
export function importorderintoredmine (excelToJson1688, excelToJsontaobao1, excelToJsontaobao2, hostname, apiKey) {
  config.hostname = hostname
  config.apiKey = apiKey

  var newOrderList = convertExcelToLogicOrderJsonResult(excelToJson1688, excelToJsontaobao1, excelToJsontaobao2)
  if (!newOrderList) {
    logger.error('order list empty')
    return
  }

  var newIssueList = convertOrderListToIssueList(newOrderList)
  if (!newIssueList || newIssueList.length === 0) {
    logger.error('issue list empty')
  }

  batchCreateIssueList(newIssueList).catch(function (ex) {
    logger.error('ex' + ex)
  }).finally(function () {
    logger.log('导入已完成')
  })
}

// eslint-disable-next-line no-unused-vars
function convertExcelToLogicOrderJsonResult (excelToJson1688, excelToJsontaobao1, excelToJsontaobao2) {
  var baseOrderInfo = {
    from: null, // "1688" 或者 "taobao"
    orderNo: null,
    sellChannelCompany: '订单销售渠道',
    orderAmount: '订单实付金额',
    orderCreateTime: '0000-00-00 00:00:00',
    orderNote: null,
    receiptName: '订单收货人姓名',
    receiptAddress: '订单收货地址',
    receiptPhone: '订单联系手机',
    productTitle: '货品标题',
    productCount: '货品数量',
    productModel: '货品代号', // 1688直接有这个货品型号
    productAttribute: '货品属性' // taobao的型号信息在货品属性中
  }

  var order1688List = []
  var orderTaobaoList = []

  try {
    order1688List = convertQm1688ExcelToOrderList(baseOrderInfo, excelToJson1688)
  } catch (ex) {
    logger.error('1688 ex' + ex)
  }
  try {
    orderTaobaoList = convertQmTaobaoExcelToOrderList(baseOrderInfo, excelToJsontaobao1, excelToJsontaobao2)
  } catch (ex) {
    logger.error('taobao ex' + ex)
  }

  var orderList = order1688List.concat(orderTaobaoList)
  logger.log('order count:' + orderList.length + '; 1688:' + order1688List.length + ', taobao:' + orderTaobaoList.length)
  return orderList
}

function convertQmTaobaoExcelToOrderList (baseOrderInfo, excelToJsontaobao1, excelToJsontaobao2) {
  // taobao自营的excel是分成两个excel导出来的
  // excelToJsontaobao1: 订单记录
  // excelToJsontaobao2: 订单对应的宝贝记录
  const tb1SheetResult = excelToJsontaobao1

  if (!tb1SheetResult || tb1SheetResult.length === 0) {
    logger.error('taobao1 sheet empty')
    return []
  }

  const tb2SheetResult = excelToJsontaobao2

  if (!tb2SheetResult || tb2SheetResult.length === 0) {
    logger.error('taobao2 sheet empty')
    return []
  }

  var part1OrderList = []
  //  传入的已是纯数据，不含标题行
  for (var i = 0; i < tb1SheetResult.length; ++i) {
    const row = tb1SheetResult[i]
    // logger.log("row:"+JSON.stringify(row));

    const newOrderInfo = Object.assign({}, baseOrderInfo)

    newOrderInfo.orderNo = row['订单编号']
    if (!newOrderInfo.orderNo) {
      logger.warn('order no empty, skip')
      continue
    }

    newOrderInfo.sellChannelCompany = '青芒淘宝自营'
    newOrderInfo.orderAmount = row['买家实际支付金额']
    newOrderInfo.orderCreateTime = row['订单创建时间']
    newOrderInfo.orderNote = row['买家留言']
    newOrderInfo.receiptName = row['收货人姓名']
    newOrderInfo.receiptAddress = row['收货地址 '] || row['收货地址']
    newOrderInfo.receiptPhone = row['联系手机']
    newOrderInfo.productTitle = row['宝贝标题 '] || row['宝贝标题']
    newOrderInfo.productCount = row['宝贝总数量']
    // newOrderInfo.productModel = ;

    newOrderInfo.from = 'taobao'
    part1OrderList.push(newOrderInfo)
  }

  // 第二张表中的宝贝信息
  var productMap = {}
  var baseProductInfo = {
    orderNo: null,
    productAttribute: null
  }
  for (let i = 1; i < tb2SheetResult.length; ++i) {
    const row = tb2SheetResult[i]

    const newProduct = Object.assign({}, baseProductInfo)

    newProduct.orderNo = row['订单编号']
    if (!newProduct.orderNo) {
      logger.warn('order no empty, skip')
      continue
    }

    newProduct.productAttribute = row['商品属性']

    productMap[newProduct.orderNo] = newProduct
  }

  // 合并出最终的order列表
  var orderList = []
  for (let i = 0; i < part1OrderList.length; ++i) {
    const order = part1OrderList[i]

    const product = productMap[order.orderNo]
    if (!product) {
      logger.warn('related product no found:' + order.orderNo)
      continue
    }

    order.productAttribute = product.productAttribute
    orderList.push(order)
    logger.log('order:' + JSON.stringify(order) + '\n')
  }

  return orderList
}

function convertQm1688ExcelToOrderList (baseOrderInfo, excelToJson1688) {
  const sheetResult = excelToJson1688

  if (!sheetResult || sheetResult.length === 0) {
    logger.error('1688 empty')
    return []
  }

  // TODO，通过第一行标题判断不同的excel来源，兼容1688和自营店

  var orderList = []
  // 传入的已是纯数据，不含标题行
  for (var i = 0; i < sheetResult.length; ++i) {
    const row = sheetResult[i]
    // logger.log("row:"+JSON.stringify(row));

    const newOrderInfo = Object.assign({}, baseOrderInfo)

    newOrderInfo.orderNo = row['订单编号']
    if (!newOrderInfo.orderNo) {
      logger.warn('order no empty, skip')
      continue
    }

    newOrderInfo.sellChannelCompany = row['买家会员名']
    newOrderInfo.orderAmount = row['实付款(元)']
    newOrderInfo.orderCreateTime = row['订单创建时间']
    newOrderInfo.orderNote = row['买家留言']
    newOrderInfo.receiptName = row['收货人姓名']
    newOrderInfo.receiptAddress = row['收货地址']
    newOrderInfo.receiptPhone = row['联系手机']
    newOrderInfo.productTitle = row['货品标题']
    newOrderInfo.productCount = row['数量']
    newOrderInfo.productModel = row['单品货号']

    newOrderInfo.from = '1688'
    orderList.push(newOrderInfo)

    logger.log('order:' + JSON.stringify(newOrderInfo) + '\n')
  }
  return orderList
}

function createQmWayBillIssueByOrderInfo (orderInfo) {
  // utf8=✓&
  // authenticity_token=AcQwFCUIeVBeLhLt5VyzjgMUETAuuOc0r1rOFzO9xr0BT1pwC5wQBvytAtjobGPEBq/KP0U3fG/ijWscl0AU+Q==&
  // copy_from=12817&
  // form_update_triggered_by=issue_status_id&
  // issue[subject]=test 2020.04.15 蔡莹分销Q53  四川 李先果  白TP老机器维修&
  // issue[is_private]=0&
  // issue[project_id]=75&
  // issue[author_id]=7&
  // issue[tracker_id]=14&
  // issue[status_id]=37&
  // issue[priority_id]=2&
  // issue[assigned_to_id]=11&
  // issue[custom_field_values][94]=蔡莹分销&
  // issue[custom_field_values][100]=长颈猫&
  // issue[custom_field_values][101]=-&
  // issue[custom_field_values][93]=1&
  // issue[custom_field_values][83]=1000&
  // issue[custom_field_values][98]=李先果 四川省达州市万源市竹峪镇   竹峪 中学大门 17738393851&
  // issue[custom_field_values][104]=1170351652625  邮政&
  // issue[custom_field_values][102]=&
  // issue[custom_field_values][92]=0&
  // issue[custom_field_values][105]=0&
  // issue[custom_field_values][107]=&
  // issue[custom_field_values][108]=1&
  // issue[custom_field_values][109]=1&
  // issue[custom_field_values][110]=电信48G&
  // issue[checklists_attributes][0][is_done]=0&
  // issue[checklists_attributes][0][subject]=&
  // issue[checklists_attributes][0][_destroy]=false&
  // issue[checklists_attributes][0][position]=1&
  // issue[checklists_attributes][0][is_section]=false&
  // issue[checklists_attributes][0][id]=&
  // issue[watcher_user_ids][]=

  // 基础的发货单信息
  var baseIssue = {
    // 所属项目:发货单
    project_id: 75,
    subject: '自动创建的发货单标题',
    // 新建
    status_id: 1,
    // 自定义字段
    custom_field_values: {
      94: '自动创建渠道',
      100: '自动创建品牌',
      101: '自动创建机型',
      93: '自动创建数量',
      83: '自动创建金额',
      98: '自动创建收地址',
      108: '自动创建按钮',
      109: '自动创建红外',
      110: '自动创建流量卡',
      104: '自动创建备注'
    }
  }

  var newIssue = Object.assign({}, baseIssue)
  newIssue.subject = parseIssueSubject(orderInfo)
  newIssue.custom_field_values[94] = parseIssueSellChannel(orderInfo)
  newIssue.custom_field_values[100] = '长颈猫'// 暂默认都是“长颈猫”
  newIssue.custom_field_values[101] = parseIssueDeviceModel(orderInfo)
  newIssue.custom_field_values[93] = orderInfo.productCount
  newIssue.custom_field_values[83] = parseIssueOrderAmount(orderInfo)
  newIssue.custom_field_values[98] = parseIssueReceiptInfo(orderInfo)
  newIssue.custom_field_values[108] = parseIssueButtonCount(orderInfo)
  newIssue.custom_field_values[109] = parseIssueInfraredCount(orderInfo)
  newIssue.custom_field_values[110] = parseIssueSimCard(orderInfo)
  newIssue.custom_field_values[104] = parseIssueOrderNote(orderInfo)
  return newIssue
}

function parseIssueSellChannel (orderInfo) {
  //   <select name="issue[custom_field_values][94]" id="issue_custom_field_values_94" class="list_cf"><option value="蔡莹分销">蔡莹分销</option>
  // <option value="尖端分销">尖端分销</option>
  // <option value="思科宇分销">思科宇分销</option>
  // <option value="美涟分销">美涟分销</option>
  // <option value="卡莎贝拉">卡莎贝拉</option>
  // <option selected="selected" value="台湾精品文具">台湾精品文具</option>
  // <option value="C端自营">C端自营</option>
  // <option value="B端自营">B端自营</option>
  // <option value="淘宝客">淘宝客</option>
  // <option value="其它">其它</option></select>

  if (orderInfo.from === 'taobao') {
    return 'C端自营'
  }

  // 以下是1688的解析

  var issueSellChannel = '其它'
  // var issueSellChannel = "未知的销售渠道";//先报错，来完善

  switch (orderInfo.sellChannelCompany) {
    case '微博微信推广工作室':
      issueSellChannel = '蔡莹分销'
      break
    case '美特达智能家居网':
    case '征道旗舰店':
      issueSellChannel = '美特达'
      break
    case '尖端科技65':
      issueSellChannel = '尖端分销'
      break
    case '神奇屋文具':
      issueSellChannel = '台湾精品文具'
      break
    case 'tb81504067':
      issueSellChannel = '思科宇分销'
      break
    case '嘿嘿嘿黑店':
      issueSellChannel = '美涟分销'
      break
    default:
      // do nothing
      logger.error('issue sell channel parse failed:' + orderInfo.sellChannelCompany)
      break
  }
  return issueSellChannel
}

function parseIssueDeviceModel (orderInfo) {
  if (orderInfo.from === '1688') {
    // 1688中配置的贷号，就是设备型号，也可从productTitle中提取
    return orderInfo.productModel
  } else if (orderInfo.from === 'taobao') {
    if (orderInfo.productAttribute.indexOf('标配版') >= 0) {
      return 'Q3'
    } else if (orderInfo.productAttribute.indexOf('高配版') >= 0) {
      return 'Q53'
    } else {
      // 以颜色的区分
      if (orderInfo.productAttribute.indexOf('桔色') >= 0 ||
      orderInfo.productAttribute.indexOf('白色') >= 0 ||
      orderInfo.productAttribute.indexOf('紫色') >= 0) {
        return 'Q3'
      } else if (orderInfo.productAttribute.indexOf('红色') >= 0 ||
      orderInfo.productAttribute.indexOf('绿色') >= 0 ||
      orderInfo.productAttribute.indexOf('蓝色') >= 0 ||
      orderInfo.productAttribute.indexOf('褐色') >= 0 ||
      orderInfo.productAttribute.indexOf('黄色') >= 0 ||
      orderInfo.productAttribute.indexOf('黑色') >= 0) {
        return 'Q53'
      } else {
        logger.error('device model failed to parse:' + orderInfo.orderNo)
      }
    }
  } else {
    logger.error('device model failed to parse:' + orderInfo.orderNo)
  }
}

function parseIssueReceiptInfo (orderInfo) {
  return orderInfo.receiptName + ' ' + orderInfo.receiptPhone + ' ' + orderInfo.receiptAddress
}

function parseIssueOrderAmount (orderInfo) {
  // 发货单只支持整数，不能带小数
  return parseInt(orderInfo.orderAmount)
}

function parseIssueButtonCount (orderInfo) {
  if (orderInfo.from === '1688') {
    return orderInfo.productTitle.indexOf('按钮') >= 0 ? 1 : 0
  } else if (orderInfo.from === 'taobao') {
    if (orderInfo.productAttribute.indexOf('按钮') >= 0) {
      return 1
    } else {
      // 以颜色的区分
      if (orderInfo.productAttribute.indexOf('白色') >= 0 ||
      orderInfo.productAttribute.indexOf('紫色') >= 0 ||
      orderInfo.productAttribute.indexOf('绿色') >= 0 ||
      orderInfo.productAttribute.indexOf('蓝色') >= 0 ||
      orderInfo.productAttribute.indexOf('黄色') >= 0 ||
      orderInfo.productAttribute.indexOf('黑色') >= 0) {
        return 1
      } else {
        return 0
      }
    }
  } else {
    logger.error('failed to parse button:' + orderInfo.orderNo)
  }
}

function parseIssueInfraredCount (orderInfo) {
  if (orderInfo.from === '1688') {
    return orderInfo.productTitle.indexOf('红外') >= 0 ? 1 : 0
  } else if (orderInfo.from === 'taobao') {
    if (orderInfo.productAttribute.indexOf('红外') >= 0) {
      return 1
    } else {
      // 以颜色的区分
      if (orderInfo.productAttribute.indexOf('紫色') >= 0 ||
      orderInfo.productAttribute.indexOf('蓝色') >= 0 ||
      orderInfo.productAttribute.indexOf('黑色') >= 0) {
        return 1
      } else {
        return 0
      }
    }
  } else {
    logger.error('failed to parse infrared:' + orderInfo.orderNo)
  }
}

function parseIssueSimCard (orderInfo) {
  // 目前，默认发"移动48G"
  if (orderInfo.from === '1688') {
    return orderInfo.productTitle.indexOf('服务') >= 0 ? '移动48G' : '无卡'
  } else if (orderInfo.from === 'taobao') {
    if (orderInfo.productAttribute.indexOf('服务') >= 0) {
      return '移动48G'
    } else {
      // 以颜色的区分
      if (orderInfo.productAttribute.indexOf('褐色') >= 0 ||
      orderInfo.productAttribute.indexOf('黄色') >= 0 ||
      orderInfo.productAttribute.indexOf('黑色') >= 0) {
        return '移动48G'
      }

      return '无卡'
    }
  } else {
    logger.error('failed to parse infrared:' + orderInfo.orderNo)
  }
}

function parseIssueOrderNote (orderInfo) {
  return '[自动:' + orderInfo.orderNo + ']' + (orderInfo.orderNote ? orderInfo.orderNote : '')
}

function parseIssueSubject (orderInfo) {
  var time = orderInfo.orderCreateTime

  // taobao的create time是字符串
  if (typeof time === 'string') {
    // 类似2020-08-10 12:00:00格式时间
    time = new Date(time)
  } else if (typeof time === 'number') {
    // excel类似42425.23489234974格式时间
    time = excelDateToJsDate(time)
    console.log('excel:', time)
  } else {
    // 默认time就是Date对象
  }

  // js month从0开始
  var zeroPrefixMonth = (time.getMonth() >= 9 ? '' : '0') + (time.getMonth() + 1)
  var zeroPrefixDate = (time.getDate() >= 10 ? '' : '0') + time.getDate()
  var subjectTime = time.getFullYear() + '.' + zeroPrefixMonth + '.' + zeroPrefixDate
  try {
    // 1688的订单省市区用空格分隔开了
    var addressParts = orderInfo.receiptAddress.split(/\s+/)
    var subjectAddress = addressParts[0] + ' ' + addressParts[1] + ' ' + addressParts[2]
  } catch (ex) {
    logger.error('subject address error:' + orderInfo.receiptAddress)
    subjectAddress = orderInfo.receiptAddress.substring(0, 10)
  }
  var subject = subjectTime + ' ' +
   parseIssueSellChannel(orderInfo) + ' ' +
   parseIssueDeviceModel(orderInfo) + ' ' +
   orderInfo.receiptName + ' ' +
   subjectAddress
  return subject
}

function excelDateToJsDate (serial) {
  var utcDays = Math.floor(serial - 25569)
  var utcValue = utcDays * 86400
  var dateInfo = new Date(utcValue * 1000)

  var fractionalDay = serial - Math.floor(serial) + 0.0000001

  var totalSeconds = Math.floor(86400 * fractionalDay)

  var seconds = totalSeconds % 60

  totalSeconds -= seconds

  var hours = Math.floor(totalSeconds / (60 * 60))
  var minutes = Math.floor(totalSeconds / 60) % 60

  return new Date(dateInfo.getFullYear(), dateInfo.getMonth(), dateInfo.getDate(), hours, minutes, seconds)
}

// eslint-disable-next-line no-unused-vars
function convertOrderListToIssueList (orderList) {
  var issueList = []
  for (let i = 0; i < orderList.length; ++i) {
    const newIssue = createQmWayBillIssueByOrderInfo(orderList[i])
    issueList.push(newIssue)
  }
  return issueList
}

function createIssuePromise (newIssue) {
  return new Promise(function (resolve, reject) {
    var createParam = {
      issue: newIssue
    }
    axios({
      method: 'post',
      url: config.hostname + '/issues.json',
      data: createParam,
      headers: {
        'X-Redmine-API-Key': config.apiKey
      }
    })
      .then(response => {
        const data = response.data
        if (data && data.issue && data.issue.id > 0) {
          logger.info('create issue ok:' + data.issue.id + '; ' + newIssue.subject + '\n')
          resolve({ isSuccess: true, success: 1, fail: 0 })
        } else {
          logger.error('create issue failed, data:', data)
          logger.info('issue:', newIssue)
          resolve({ isSuccess: false, success: 0, fail: 1 })
        }
      })
      .catch(err => {
        logger.error('ex' + err)
      })
  })
}

// eslint-disable-next-line no-unused-vars
async function batchCreateIssueList (newIssueList) {
  logger.log('\n\n ============= BATCH CREATE ISSUE =========== \n')

  var createResultList = []
  var totalSuccessCount = 0
  for (let i = 0; i < newIssueList.length; ++i) {
    const createResult = await createIssuePromise(newIssueList[i])
    createResultList.push(createResult)
    totalSuccessCount += createResult.success
  }

  logger.log('\n ============= RESULT =========== \n')
  logger.log(JSON.stringify(createResultList))
  logger.log('\n success:' + totalSuccessCount + '; total:' + createResultList.length)
  logger.log('===============================')
}
